<?php

/**
 * Created by PhpStorm.
 * Author: kaodou
 * Date: 2017/12/19
 * Time: 14:18
 */

namespace App\Http\Admin\Purchase\Controllers;
use App\Http\Admin\Website\Models\Menu;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\StockIn;
use App\Engine\Func;
use App\Engine\Stock as StockEngine;

use Framework\BaseClass\Http\Admin\Controller;

class IndexController extends Controller
{
    public function add(){
        $productId = request('product_id');

        $adminUser = request()->user('admin')->toArray();

        if (request()->isMethod('post')) {
            $StockInModel = new StockIn();

            $params = request()->all();

            $stockInData = [
                'unit_price' => isset($params['unit_price'])?$params['unit_price']:0,
                'distribution_company' => isset($params['distribution_company'])?$params['distribution_company']:0,
                'distribution_time' => isset($params['distribution_time'])?strtotime($params['distribution_time']):time(),
                'contact_number' => $params['contact_number'],
//                'uid' => $adminUser['id'],//前台、跟后台添加用的UID不同
            ];
            if($stockInId = $StockInModel->insertOneData($stockInData,'id')){
                $water_no = StockEngine::createWaterNo();
                $stockData[] = [
                    'number' => $params['number'],
                    'supplier_id' => $params['supplier_id'],
                    'total_price' => $params['number']*$params['unit_price'],
                    'product_id' => $productId,
                    'company_id' => $adminUser['company_id'],
//                'operate_uid' => $adminUser['id'],
                    'water_no' => $water_no,
                    'relate_type' => 3,
                    'relate_id' => $stockInId
                ];
                $stockResult = StockEngine::addStockData($stockData);
                return $this->ajaxSuccess();
            }else{
                return $this->ajaxFail();
            }
        }

        $productModel = new Product();
        $where = ['id' => $productId];
        $info = $productModel->getOneData($where);
        $info->img_url = Func::getImgUrlById($info->img_id);


        return $this->view('add',compact('info'));
    }
}